package com.situ.allaia.interceptor;

import com.situ.allaia.model.AdminUser;
import com.situ.allaia.model.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

public class LoginInterceptor implements HandlerInterceptor {
    public static final String CURRENT_LOGIN_USER_KEY = "@#current_user_login";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
       User user = (User) session.getAttribute(CURRENT_LOGIN_USER_KEY);
        if (user==null){
            //登录后重定向到先前的地址,作用是跳转到登录之前的页面
            String redirectUrl = request.getParameter("redirectUrl");
            if (StringUtils.hasText(redirectUrl)){
                session.setAttribute("redirectUrl",redirectUrl);
            }
            System.out.println(request.getContextPath());
            response.sendRedirect(request.getContextPath()+"/user/login");
            return false;
        }
        return true;
    }
}
